package com.epoint.mybatispluslearning.configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.injector.methods.LogicDeleteByIdWithFill;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@MapperScan("com.epoint.mybatispluslearning")
@Configuration
public class MybatisPlusConfiguration {

    /**
     * 注册自动填充的策略
     * @return
     */
    @Bean
    public MetaObjectHandler myMetaObjectHandler(){
        return new MetaObjectHandler(){
            @Override
            public void insertFill(MetaObject metaObject) {
                System.out.println("start insert fill ....");
                this.setFieldValByName("createdate", new Date(), metaObject);
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                System.out.println("start update fill ....");
                this.setFieldValByName("updateTime", new Date(), metaObject);
            }
        };
    }

    /**
     * 新版
     * 乐观锁的实现
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor_leguansuo() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor_fenye() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }
}
